﻿using System.IO;
using System.Net;
using System.Text;
using Fizzler.Systems.HtmlAgilityPack;
using HtmlAgilityPack;

namespace HtmlDeploy
{
    public class Css
    {
        private readonly HtmlDocument html;
        private readonly string path;

        public Css(string path)
        {
            html = new HtmlDocument();
            html.Load(path);

            this.path = path.Substring(0, path.LastIndexOf(@"\") + 1);
        }

        public string Process()
        {
            var csses = html.DocumentNode.QuerySelectorAll("link, style");

            var sb = new StringBuilder();

            foreach (var css in csses)
            {
                var href = css.GetAttributeValue("href", "");

                if (string.IsNullOrEmpty(href))
                    sb.AppendLine(css.InnerText);
                else if (href.StartsWith("http"))
                    sb.AppendLine(GetExternalWeb(href));
                else
                    sb.AppendLine(GetLocalExternal(href));
            }

            return sb.ToString();
        }

        private string GetLocalExternal(string src)
        {
            using (var sr = new StreamReader(path + src))
            {
                return sr.ReadToEnd();
            }
        }

        private string GetExternalWeb(string url)
        {
            var webRequest = WebRequest.Create(url);
            var response = (HttpWebResponse)webRequest.GetResponse();

            if (response == null)
                return "";

            try
            {
                var stream = response.GetResponseStream();

                if (stream == null)
                    return "";

                var streamReader = new StreamReader(stream, true);

                try
                {
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    streamReader.Close();
                }
            }
            finally
            {
                response.Close();
            }
        }
    }
}
